import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null)
  const isAuthenticated = ref(false)
  const isInitialized = ref(false) // 添加初始化状态

  function login(userData, token) {
    user.value = userData
    isAuthenticated.value = true
    localStorage.setItem('token', token)
    localStorage.setItem('user', JSON.stringify(userData))
  }

  function logout() {
    user.value = null
    isAuthenticated.value = false
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  function initialize() {
    try {
      const token = localStorage.getItem('token')
      const userData = localStorage.getItem('user')
      
      // 只有当两者都存在时才尝试解析
      if (token && userData && userData !== 'undefined') {
        user.value = JSON.parse(userData)
        isAuthenticated.value = true
      } else {
        // 如果数据无效，清除存储
        logout()
      }
    } catch (error) {
      console.error('初始化认证状态失败:', error)
      // 解析失败时清除无效数据
      logout()
    } finally {
      isInitialized.value = true
    }
  }

  return { user, isAuthenticated, isInitialized, login, logout, initialize }
})